package com.lanou.sfu.songforu.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.lanou.sfu.songforu.R;
import com.lanou.sfu.songforu.activity.MainActivity;
import com.lanou.sfu.songforu.base.BaseFragment;
import com.lanou.sfu.songforu.tools.WiperSwitch;
import com.lanou.sfu.songforu.utils.cache.DataCleanManager;

import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by dllo on 15/11/4.
 */
public class SettingFragment extends BaseFragment {
    private View v;
    private WiperSwitch mSwitch;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private RelativeLayout cleanBtn;
    private TextView cleanCacheSize,titleTv;
    private LinearLayout back_title;
    private Button exit,timingClose;
    CountDownTimer countDownTimer = null;
    // 选定关闭小时
    int closeHour = 0;
    // 选定关闭分钟
    int closeMinutes = 0;
    Calendar c = null;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.fragment_setting,null);
        mSwitch = (WiperSwitch) v.findViewById(R.id.left_menu_switch);
        cleanBtn = (RelativeLayout) v.findViewById(R.id.cleanCache);
        cleanCacheSize = (TextView) v.findViewById(R.id.cleanCacheSize);
        back_title = (LinearLayout) v.findViewById(R.id.back_btn);
        exit = (Button) v.findViewById(R.id.setting_exit);
        timingClose = (Button) v.findViewById(R.id.timingClose);
        titleTv = (TextView) v.findViewById(R.id.set_back_text);
        return v;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 设置标题
        titleTv.setText(R.string.setting);
        // JPush
        sharedPreferences = getActivity().getSharedPreferences("JPush", Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        // 获得cache大小,显示
        try {
            cleanCacheSize.setText(DataCleanManager.getCacheSize(getActivity().getCacheDir()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        // JPush开关监听
        mSwitch.setOnChangedListener(new WiperSwitch.OnChangedListener() {
            @Override
            public void OnChanged(WiperSwitch wiperSwitch, boolean checkState) {
                if (checkState == false) {
                    Set<Integer> days = new HashSet<>();
                    JPushInterface.setPushTime(getActivity(), days, 0, 0);
                    Toast.makeText(getActivity(), "关闭推送", Toast.LENGTH_LONG).show();
                    editor.putBoolean("JPush", false);
                    editor.commit();
                    Log.i("push", "1111");
                } else {
                    Set<Integer> days = new HashSet<>();
                    days.add(0);
                    days.add(1);
                    days.add(2);
                    days.add(3);
                    days.add(4);
                    days.add(5);
                    days.add(6);
                    JPushInterface.setPushTime(getActivity(), days, 6, 23);
                    editor.putBoolean("JPush", true);
                    editor.commit();
                    Log.i("push", "2222");
                }
            }
        });
        // 清理缓存按键监听
        cleanBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DataCleanManager.deleteFolderFile(getActivity().getCacheDir().toString(), true);

                try {
                    cleanCacheSize.setText(DataCleanManager.getCacheSize(getActivity().getCacheDir()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        // 返回按键监听,与侧滑栏有冲突,解决办法为跳转至主页面
        back_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MainActivity.class);
                getActivity().finish();
                startActivity(intent);
            }
        });

        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });

        timingClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (sharedPreferences.getBoolean("JPush", true))
            mSwitch.setChecked(true);
        else
            mSwitch.setChecked(false);
    }

    // 弹出TimePicker
    private void alertDialog() {
        final TimeDialog timeDialog = new TimeDialog();
        View myView = null;
        LayoutInflater inflater = LayoutInflater
                .from(getActivity());
        myView = inflater.inflate(R.layout.fragment_select_closetime, null);
        timeDialog.ensureButton = (Button) myView.findViewById(R.id.button01);
        timeDialog.timePicker = (TimePicker) myView.findViewById(R.id.timePicker);

        // 设置为24小时制
        timeDialog.timePicker.setIs24HourView(true);
        // 初始化小时
        timeDialog.timePicker.setCurrentHour(0);

        // 初始化分钟
        timeDialog.timePicker.setCurrentMinute(0);
        timeDialog.cancelButton = (Button) myView.findViewById(R.id.button02);
        final AlertDialog dialog = new AlertDialog.Builder(
                getActivity()).setView(myView).create();
        dialog.show();

        // 确定按钮执行操作
        timeDialog.ensureButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                // 获取用户选定时间
                closeHour = ((timeDialog.timePicker.getCurrentHour()) * 3600000);
                closeMinutes = ((timeDialog.timePicker.getCurrentMinute()) * 60000);
                final int closeTime = closeHour + closeMinutes;
                final int closeTimes = closeTime/1000;
                countDownTimer = new CountDownTimer(closeTime, 1000) {

                    @Override
                    public void onTick(long millisUntilFinished) {

                        if ((millisUntilFinished / 1000) == closeTimes - 1) {
                            Toast.makeText(getActivity(),
                                    "聚宝盒将在" + (closeTime / 60000) + "分钟后关闭", Toast.LENGTH_LONG).show();
                        }
                    }
                    @Override
                    public void onFinish() {

                        System.exit(0);
                    }
                };
                countDownTimer.start();
                dialog.dismiss();
            }
        });

        // 取消按钮退出操作
        timeDialog.cancelButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                countDownTimer.cancel();
                dialog.dismiss();
            }
        });
    }

    public class TimeDialog {
        private Button ensureButton;
        private Button cancelButton;
        private TimePicker timePicker;
    }

}
